# -*- coding: utf-8 -*-
"""
Created on Tue Dec  6 09:18:04 2022

@author: DELL
"""


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
import pyqtgraph as pg
from serialAnalyse import *
import time
import numpy as np
import serial
import re

frame_data_period_ms=1000
class mainWin(QtWidgets.QWidget,Ui_Form):
    
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        #initialize a timer here to get data
        self.timer=QtCore.QTimer()
        self.timer.timeout.connect(self.getSerial)
      
        ##initialize a serial port here
        self.ser=serial.Serial()
        self.ser.baudrate    = 115200
        self.ser.timeout     = 1
        self.portList=[]
        
        #实例化绘图窗口
        self.plotwidget1=pg.PlotWidget(name="plot1",background='w')
        self.plotwidget2=pg.PlotWidget(name="plot2",background='w')
        
        ##the beginning string and the closing string
        self.firstPlotString="" 
        self.secondPlotString="" 
        self.firstPlotdata=np.zeros(512)
        
        #将实例化后的窗口添加到布局
        self.verticalLayout.addWidget(self.plotwidget1)
        self.verticalLayout.addWidget(self.plotwidget2)
        #设置坐标轴标签
        self.plotwidget1.setLabel("left","Chest Displacement")
        self.plotwidget1.setLabel("bottom","Time")
        self.plotwidget1.setYRange(-4,4)
        self.plotwidget1.setLabel("top","Respiration Waveform")
        self.plotwidget2.setLabel("left","FFT")
        self.plotwidget2.setLabel("bottom","HeartbeatRate")
        self.plotwidget2.setLabel("top","Heartbeat Result")

        #实例化呼吸绘图曲线
        self.firstPlot=self.plotwidget1.plot(pen=pg.mkPen(color='r'))        
        #实例化心跳绘图曲线
        self.secondPlot=self.plotwidget2.plot(pen=pg.mkPen(color='r'))
        if self.portNum.currentText()=="":  #no serial prot is availabe
            self.findPorts()
            self.portNum.addItems(self.portList)     
  
    def startProcess(self):
         
             
         if self.timer.isActive() ==False:  ##means no process is running
             if self.portNum.currentText()=="":
                 QtWidgets.QMessageBox().about(self,"Warning","Pls select COM# first")

             else:
                 self.ser.port=self.portNum.currentText()
                 try:
                     self.ser.open()                     
                     time.sleep(0.1)
                     self.ser.reset_input_buffer()
                     #print("open com port successfully")
                     self.serialText.clear()
                     self.serialText.appendPlainText("Open COM PORT Successfully")

                 except:
                     #self.serialText.clear()
                     self.serialText.appendPlainText("Failed to open COM Port")
                         
             
             self.timer.start(frame_data_period_ms)  #单位毫秒
             self.startButton.setText("Stop")
             self.firstPlotString=self.firstHeadLine.text()+r"\r\n(.*?)"+self.firstTailLine.text()
             self.secondPlotString=self.secondHeadLine.text()+r"\r\n(.*?)"+self.secondTailLine.text()
         else:
             self.timer.stop()
             self.startButton.setText("Start")
             self.ser.close()
             self.serialText.appendPlainText("Successfully to close COM Port")

    def findPorts(self):
        
        for i in range(0,40):
            port_name = 'COM' + str(i)
            print(port_name)
            self.ser.port = port_name
            try:
                if self.ser.is_open:
                    print('will close %s' %(port_name))
                    self.ser.close()
                self.ser.open()
                if self.ser.is_open:
                    self.portList.append(port_name)
                    self.ser.close()
            except:
                pass
    
    
    def getSerial(self):

        recvStr=self.ser.read_all().decode('ascii', 'ignore')
        self.serialText.appendPlainText(recvStr)
        if ("respiration start" in recvStr) and ("respiration stop" in recvStr):
                      
            ##extract the first plot data
            dataStr=re.findall(r"respiration start\r\n(.*?)respiration stop",recvStr,re.S)
            if len(dataStr):
                dataArray=np.array(dataStr[0].split("\r\n")) ##split into num str 
                plotData=dataArray[:-1] ##last one is "",should be deleted
                plotData=plotData.astype(float)
                #self.firstPlotdata=np.append(self.firstPlotdata[20:],plotData[-20:])
                self.firstPlotdata=plotData
                ##plot data
                self.firstPlot.setData(y=self.firstPlotdata)
            ##extract the second plot data
            dataStr=re.findall(r"Find Peaks\r\n(.*?)Find Peaks End",recvStr,re.S)
            if len(dataStr):
                dataArray=np.array(dataStr[0].split("\r\n")) ##split into num str 
                plotData=dataArray[:-1] ##last one is "",should be deleted
                plotData=plotData.astype(float)
                ##plot data
                self.secondPlot.setData(x=np.arange(23,51)*1200/512,y=plotData)
        else:
            #print("real all left and then get the whole frame")
            self.serialText.appendPlainText(self.ser.read(self.ser.inWaiting()).decode("ascii","ignore"))
            #self.ser.reset_input_buffer()

                
                
            
            
        
        
    
                
    
    
    
    
    # def drawdata(self,msg):
    #     #将数据打印的文本框中
        
    #     self.textEdit.setPlainText(displaystr)
    #     #绘制呼吸图像 
    #     self.breathT1.setData(y=msg[0,:])
    #     self.breathT2.setData(y=msg[5,:])
        
    #     #绘制呼吸图像 
    #     self.heartT1.setData(y=msg[1,:])
    #     self.heartT2.setData(y=msg[6,:])
    #     #绘制呼吸图像 
    #     self.rangeT1.setData(y=msg[2,:])
    #     self.rangeT2.setData(y=msg[7,:])
            
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = mainWin()
    Form.show()
    sys.exit(app.exec_())      
    